#加载数据集
import pandas as pd
from spyder.plugins.ipythonconsole.widgets.client import KERNEL_ERROR

#导入数据集
names = ['label','a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11','a12','a13']
dataset = pd.read_csv("D:\\机器基础\\yinmujiu\\ml-lesson\\03_dataset\\item4\\wine-clean.data",names=names)
data = dataset.iloc[range(0,178),range(1,14)]
target = dataset.iloc[range(0,178),range(0,1)].values.reshape(1,178)[0]
print(data)
#进行数据标准化
from sklearn import preprocessing
cdata = preprocessing.StandardScaler().fit_transform(data)
print(cdata)
#找到最优的K值
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score

x,y =cdata,target
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0)

k_range = range(1,15)
k_error =[]

for k in k_range:
    model = KNeighborsClassifier(k)
    scores = cross_val_score(model,x,y,cv=5,scoring='accuracy')
    k_error.append(1-scores.mean())
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.plot(k_range,k_error,'r-')
plt.xlabel('k的取值')
plt.ylabel('预测误差')
plt.show()

#使用最优的K=9来训练模型
from sklearn.metrics import accuracy_score

model = KNeighborsClassifier(9)
model.fit(x_train,y_train)
#对模型进行评估
pred = model.predict(x_test)
ac = accuracy_score(y_test,pred)
print("模型预测准确率：",ac)
print("测试集的预测标签：",pred)
print("测试集的真实标签：",y_test)